import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/common_tab_bar.dart';
import 'package:casdon/modules/recipe/providers/recipe_provider.dart';
import 'package:casdon/modules/recipe/ui/screen/recipe_curated_screen.dart';
import 'package:casdon/modules/recipe/ui/screen/recipe_favorites_screen.dart';
import 'package:casdon/modules/recipe/ui/screen/recipe_smart_screen.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_cloud_list_notifier.dart';
import 'package:casdon/modules/recipe/ui/widgets/search_placeholder_bar.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class RecipeHomeScreen extends ConsumerStatefulWidget {
  const RecipeHomeScreen({super.key});

  @override
  ConsumerState<RecipeHomeScreen> createState() => _RecipeHomeScreenState();
}

class _RecipeHomeScreenState extends ConsumerState<RecipeHomeScreen>
    with TickerProviderStateMixin {
  TabController? _tabController;
  final ValueNotifier<bool> _refreshFavorites = ValueNotifier(false);
  int _tabLength = 0;
  bool _initialized = false;

  @override
  void initState() {
    super.initState();
    final tabs = ref.read(tabProvider);
    _initController(tabs.length());

    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!_initialized &&
          _tabController != null &&
          _tabController!.length > 1) {
        _tabController!.index = 1;
        _initialized = true;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    ref.watch(tabProvider); // 确保外部状态变更时可响应
    final smartState = ref.watch(recipeCloudListNotifierProvider);

    // 智能页是否有可展示数据：必须有设备且任一设备菜谱列表非空
    final bool hasSmart = smartState.maybeWhen(
      data: (s) {
        if (s.devList.isEmpty) return false;
        for (final dc in s.data) {
          if (dc.data.isNotEmpty) return true;
        }
        return false;
      },
      orElse: () => false,
    );

    final List<String> labels = ["收藏", "精选", if (hasSmart) "智能"]; // 动态标签

    // ✅ 如果 tab 数量发生变化，重新创建 controller
    if (_tabLength != labels.length) {
      // 记录旧 index，重建后保持不变（或压到范围内）
      final prevIndex = _tabController?.index ?? 0;
      _initController(
        labels.length,
        initialIndex: prevIndex.clamp(0, labels.length - 1),
      );
    }

    return Scaffold(
      body: SafeArea(
        top: false,
        child: Stack(
          children: [
            Positioned.fill(
              child: Image.asset(
                Assets.images.screenHeader.path,
                fit: BoxFit.cover,
                width: double.infinity,
                alignment: Alignment.topCenter,
              ),
            ),
            Column(
              children: [
                SizedBox(height: 0.h + MediaQuery.of(context).padding.top),

                /// 搜索栏
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 12.w),
                  child: SearchPlaceholderBar(
                    onTap: () {
                      _handleSearchClick(context);
                    },
                    placeholder: "搜索",
                  ),
                ),

                /// 顶部 TabBar
                Transform.translate(
                  offset: Offset(-40.w, 0),
                  child: CommonTabBar(
                    tabLabels: labels,
                    isScrollable: true,
                    controller: _tabController!,
                  ),
                ),

                /// 内容区域
                Expanded(
                  child: TabBarView(
                    controller: _tabController!,
                    children: [
                      RecipeFavoritesScreen(
                        refreshNotifier: _refreshFavorites,
                        onGoExplore: () {
                          // 切换到“推荐”tab（索引1）
                          if (_tabController != null &&
                              _tabController!.length > 1) {
                            _tabController!.animateTo(1);
                          }
                        },
                      ),
                      RecipeCuratedScreen(onRefreshed: _handleCuratedRefreshed),
                      if (hasSmart) const RecipeSmartScreen(),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 初始化 TabController
  void _initController(int length, {int? initialIndex}) {
    final prev = _tabController?.index ?? 0;
    _tabController?.dispose();
    final initIdx = (initialIndex ?? prev).clamp(
      0,
      (length > 0 ? length - 1 : 0),
    );
    _tabController = TabController(
      length: length,
      vsync: this,
      initialIndex: initIdx,
    );
    _tabController!.addListener(() {
      if (_tabController!.indexIsChanging) return;

      if (_tabController!.index == 0) {
        // 通知 RecipeFavoritesScreen 刷新
        _refreshFavorites.value = true;
      }
    });
    _tabLength = length;
  }

  @override
  void dispose() {
    _tabController?.dispose();

    _refreshFavorites.dispose();
    super.dispose();
  }

  void _handleSearchClick(BuildContext context) {
    RecipeSearchRoute().push(context);
  }

  void _handleCuratedRefreshed() {
    ref.read(recipeCloudListNotifierProvider.notifier).refresh();
  }
}
